﻿package com.vinyl.net
{
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.*;
	import flash.net.URLRequest;
	import flash.display.MovieClip;
	import flash.system.LoaderContext;
	
	public class ImageLoader
	{
		public var loader:Loader = new Loader();
		
		public var onComplete:Function;
		public var onError:Function;
		public var onProgress:Function;
		
		private var _container:MovieClip;
		private var _request:URLRequest;
		
		public var data:*;
		
		public function ImageLoader():void
		{
			container = new MovieClip();
			loader.contentLoaderInfo.addEventListener( Event.COMPLETE, completeHandler );
			loader.contentLoaderInfo.addEventListener( IOErrorEvent.IO_ERROR, ioErrorHandler );
		}
		
		public function load(url:String, lc:LoaderContext = null ):void
		{ 
			_request = new URLRequest( url );
			if ( lc ) loader.load( _request, lc );
			else loader.load( _request );
		}
		
		public function set container( mc:MovieClip ):void
		{
			_container = mc;
			loader.contentLoaderInfo.addEventListener( ProgressEvent.PROGRESS,  sendParameters( progressHandler, _container ) );
		}
		
		public function get container():MovieClip
		{
			return _container;
		}
		
		private function completeHandler( event:Event ):void
		{
			if( onComplete != null ) onComplete( event, this );
		}
		
		private function ioErrorHandler( event:Event ):void
		{
			if( onError != null ) onError( event, this );
		}	
		
		private function progressHandler( event:ProgressEvent, owner, arg ):void
		{
			if( onProgress != null ) onProgress( event, owner );
			if( 100 * event.bytesLoaded  / event.bytesTotal >= 100 ) loader.contentLoaderInfo.removeEventListener( ProgressEvent.PROGRESS, arg ); 
		}
		
		private function sendParameters( func, arg ):Function
		{ 
			return function(e):void
			{ 
				func.apply( this, [e].concat( arg, arguments.callee ) ); 
			} 
		} 
		
		public function destory():void
		{
			_container.removeChild( loader );
			onComplete = null;
			onError = null;
			onProgress = null;
			onComplete = null;
			
			try 
			{
				loader.close();
			} catch ( error : Error ){}
		}
	}
}